<template>
  <div class="comment-box">
    <div
      v-clickoutside="hideReplyBtn"
      @click="inputFocus"
      class="my-reply"
    >
      <el-avatar
      v-if="ReplyList.user"
        class="header-img"
        :size="40"
        :src="ReplyList.user.portrait"
      ></el-avatar>
      <div class="reply-info">
        <div
          tabindex="0"
          contenteditable="true"
          id="replyInput"
          spellcheck="false"
          placeholder="输入评论..."
          class="reply-input"
          @focus="showReplyBtn"
          @input="onDivInput($event)"
        ></div>
      </div>
      <div class="reply-btn-box" v-show="btnShow">
        <el-button
          class="reply-btn"
          size="medium"
          @click="sendComment"
          type="primary"
        >
          发表评论
        </el-button>
      </div>
    </div>

    <div
      v-for="(item, i) in comments"
      :key="i"
      class="box-card author-title reply-father"
      v-if="ReplyList.user"
    >
      <el-avatar
        class="header-img"
        :size="40"
        :src="ReplyList.user.portrait"
      ></el-avatar>
      <div class="author-info">
        <span class="author-name">{{ ReplyList.user.username }}</span>
        <span class="author-time">{{
          new Date(ReplyList.user.registrationTime).toLocaleString()
        }}</span>
      </div>
      <div class="icon-btn">
        <span
          @click="showReplyInput(i, '0', ReplyList.user.username, item.id)"
          v-model="commentNum"
        >
          <i class="iconfont icon-chakantiezihuifu"></i>
          {{ item.commentNum }}
        </span>
        <span
          class="xin"
          @click="countlikeNumber('1', i, item.id)"
          v-model="like"
        >
          <i class="iconfont icon-dianzan3" v-if="item.isLike"></i>
          <i class="iconfont icon-dianzan3" v-else></i>
          {{ item.like }}
        </span>
      </div>
      <div class="talk-box">
        <p>
          <span class="reply">{{ item.comment }}</span>
        </p>
      </div>
      <div class="reply-box">
        <div v-for="(reply, j) in item.reply" :key="j" class="author-title">
          <el-avatar
            class="header-img"
            :size="40"
            :src="reply.fromHeadImg"
          ></el-avatar>
          <div class="author-info">
            <span class="author-name">{{ reply.from }}</span>
            <span class="author-time">{{ reply.time }}</span>
          </div>
          <div class="icon-btn">
            <span
              @click="showReplyInput(i, j, reply.from, reply.id)"
              v-model="commentNum"
            >
              <i class="iconfont icon-chakantiezihuifu"></i>
              {{ reply.commentNum }}
            </span>
            <span @click="countlikeNumber('2', i, j, reply)" v-model="like">
              <i class="iconfont icon-dianzan3"></i>
              {{ reply.like }}
            </span>
          </div>
          <div class="talk-box">
            <p>
              <span>回复 {{ reply.to }}:</span>
              <span class="reply">{{ reply.comment }}</span>
            </p>
          </div>
          <div class="reply-box"></div>
        </div>
      </div>
      <div
        v-show="_inputShow(i)"
        class="my-reply my-comment-reply"
        v-if="ReplyList.user"
      >
        <el-avatar
          class="header-img"
          :size="40"
          :src="ReplyList.user.portrait"
        ></el-avatar>
        <div class="reply-info">
          <div
            tabindex="0"
            contenteditable="true"
            spellcheck="false"
            placeholder="输入评论..."
            @input="onDivInput($event)"
            class="reply-input reply-comment-input"
          ></div>
        </div>
        <div class="reply-btn-box">
          <el-button
            class="reply-btn"
            size="medium"
            @click="sendCommentReply(i)"
            type="primary"
          >
            发表回复
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { section, sendMessage } from '@/api/services/article.services'
const clickoutside = {
  // 初始化指令
  bind (el, binding, vnode) {
    function documentHandler (e) {
      // 这里判断点击的元素是否是本身，是本身，则返回
      if (el.contains(e.target)) {
        return false
      }
      // 判断指令中是否绑定了函数
      if (binding.expression) {
        // 如果绑定了函数 则调用那个函数，此处binding.value就是handleClose方法
        binding.value(e)
      }
    }
    // 给当前元素绑定个私有变量，方便在unbind中可以解除事件监听
    el.vueClickOutside = documentHandler
    document.addEventListener('click', documentHandler)
  },
  update () {},
  unbind (el, binding) {
    // 解除事件监听
    document.removeEventListener('click', el.vueClickOutside)
    delete el.vueClickOutside
  }
}
export default {
  name: 'ArticleComment',
  props: {
    value: {
      type: Number
    }
  },
  data () {
    return {
      commentNum: this.value,
      like: this.value,
      ReplyList: {},
      CommentList: {},
      currentDate: '',
      btnShow: false,
      index: '0',
      replyComment: '',
      subIndex: '0',
      myName: 'Lana Del Rey',
      myId: 19870621,
      to: '',
      toId: -1,
      comments: [
        {
          name: 'Lana Del Rey', // 吧主名
          id: 19870621, // 用户id
          // 用户头像
          headImg:
            'https://img2.baidu.com/it/u=3631451984,3719946192&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
          // comment: "我发布一张新专辑Norman Fucking Rockwell,大家快来听啊", // 评论内容
          time: '2019年9月16日 18:43', // 评论时间
          commentNum: 0, // 评论数
          like: 0, // 点赞量
          isLike: false,
          isCollect: false,
          likeListId: [], // 存放已点赞用户的id
          collectListId: [], // 存放已收藏用户的id
          inputShow: false,
          reply: [
            {
              from: 'Taylor Swift', // 其他用户的用户名
              fromId: 19891221, // id
              // 头像
              fromHeadImg:
                'https://img2.baidu.com/it/u=3631451984,3719946192&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
              to: 'Lana Del Rey', // 本吧主，与上面name: 'Lana Del Rey'同一个
              toId: 19870621, // 吧主id
              comment: '我很喜欢你的专辑！！', // 评论
              time: '2019年9月16日 18:43', // 时间
              commentNum: 1, // 评论数
              like: 0, // 点赞量
              collect: 0, // 收藏量
              isLike: false,
              isCollect: false,
              likeListId: [],
              collectListId: [],
              inputShow: false
            }
          ]
        }
      ]
    }
  },
  directives: { clickoutside },
  mounted () {
    this.getReplyList(this.$route.query.sid, this.$route.query.pid)
    this.getSeedMessage(this.$route.query.pid)
  },
  methods: {
    async getReplyList (sid, pid) {
      this.ReplyList.sid = sid
      this.ReplyList.pid = pid
      this.ReplyList.uid = this.$store.state.user.uid
      const data = await section(sid, pid, this.ReplyList)
      // console.log(this.ReplyList);
      console.log(data)
      if (data === null) return this.$message.error('加载失败，稍后重试！')
      this.ReplyList = data
    },
    async getSeedMessage (pid) {
      sendMessage({
        pid,
        uid: this.$store.state.user.uid
      })
    },

    inputFocus () {
      const replyInput = document.getElementById('replyInput')
      replyInput.style.padding = '8px 8px'
      replyInput.style.border = '2px solid blue'
      replyInput.focus()
    },
    showReplyBtn () {
      this.btnShow = true
    },
    hideReplyBtn () {
      this.btnShow = false
    },
    showReplyInput (i, j, name, id) {
      this.comments[this.index].inputShow = false
      this.index = i
      this.comments[i].inputShow = true
      this.to = name
      this.toId = id
      this.subIndex = j == '0' ? '0' : j
    },
    addlikeNumber (i, id) {
      const list = this.comments[i].likeListId
      // console.log(i, name, id)
      if (list.length === 0) {
        // 在已经点赞的列表中未找到userId
        this.comments[i].isLike = true
        this.comments[i].like += 1
        this.comments[i].likeListId.push(id)
        console.log(
          '点赞+1',
          this.comments[i].isLike,
          this.comments[i].like,
          this.comments[i].likeListId
        )
      } else {
        const index = list.indexOf(this.myId)
        this.comments[i].isLike = false
        this.comments[i].like -= 1
        this.comments[i].likeListId.splice(index, 1)
        console.log(
          '点赞-1',
          this.comments[i].isLike,
          this.comments[i].likeListId
        )
      }
    },
    countlikeNumber (type, i, j, id) {
      const text = type === '1' ? this.comments[i] : this.comments[i].reply[j]
      const list = text.likeListId
      if (list.length === 0) {
        // 在已经点赞的列表中未找到userId
        text.isLike = true
        text.like += 1
        text.likeListId.push(id)
        console.log('点赞+1', text.isLike, text.like, text.likeListId)
      } else {
        const index = list.indexOf(this.myId)
        text.isLike = false
        text.like -= 1
        text.likeListId.splice(index, 1)
        console.log('点赞-1', text.isLike, text.likeListId)
      }
    },
    _inputShow (i) {
      return this.comments[i].inputShow
    },
    sendComment () {
      if (!this.replyComment) {
        this.$message({
          showClose: true,
          type: 'warning',
          message: '评论不能为空'
        })
      } else {
        const a = {}
        const input = document.getElementById('replyInput')
        const timeNow = new Date().getTime()
        const time = this.dateStr(timeNow)
        a.name = this.myName
        a.comment = this.replyComment
        a.headImg = this.myHeader
        a.time = time
        a.commentNum = 0
        a.like = 0
        a.id = this.myId
        a.reply = []
        a.isLike = false
        a.likeListId = []
        this.comments.push(a)
        this.replyComment = ''
        input.innerHTML = ''
      }
    },
    sendCommentReply (i) {
      if (!this.replyComment) {
        this.$message({
          showClose: true,
          type: 'warning',
          message: '回复不能为空'
        })
      } else {
        const a = {}
        const timeNow = new Date().getTime()
        const time = this.dateStr(timeNow)
        a.from = this.myName
        a.to = this.to
        a.fromHeadImg = this.myHeader
        a.comment = this.replyComment
        a.time = time
        a.commentNum = 0
        a.like = 0
        a.isLike = false
        a.likeListId = []
        console.log(
          ' this.comments[i].reply+++++++++++',
          this.comments[i].reply,
          this.subIndex
        )
        if (this.subIndex === '0') {
          this.comments[i].commentNum += 1
        } else {
          this.comments[i].reply[this.subIndex].commentNum += 1
        }
        this.comments[i].reply.push(a)
        this.replyComment = ''
        document.getElementsByClassName('reply-comment-input')[i].innerHTML =
          ''
      }
    },
    onDivInput: function (e) {
      this.replyComment = e.target.innerHTML
    },
    dateStr (date) {
      // 获取js 时间戳
      let time = new Date().getTime()
      // 去掉 js 时间戳后三位，与php 时间戳保持一致
      time = parseInt((time - date) / 1000)
      // 存储转换值
      let s
      if (time < 60 * 10) {
        // 十分钟内
        return '刚刚'
      } else if (time < 60 * 60 && time >= 60 * 10) {
        // 超过十分钟少于1小时
        s = Math.floor(time / 60)
        return s + '分钟前'
      } else if (time < 60 * 60 * 24 && time >= 60 * 60) {
        // 超过1小时少于24小时
        s = Math.floor(time / 60 / 60)
        return s + '小时前'
      } else if (time < 60 * 60 * 24 * 30 && time >= 60 * 60 * 24) {
        // 超过1天少于30天内
        s = Math.floor(time / 60 / 60 / 24)
        return s + '天前'
      } else {
        // 超过30天ddd
        var date = new Date(parseInt(date))
        return (
          date.getFullYear() +
          '/' +
          (date.getMonth() + 1) +
          '/' +
          date.getDate()
        )
      }
    }
  }
}
</script>
<style lang="less" scoped>
.my-reply {
  background-color: #fafbfc;
  .header-img {
    display: inline-block;
    vertical-align: top;
  }
  .reply-info {
    display: inline-block;
    margin-left: 5px;
    width: 90%;
    //根据屏幕宽度自适应
    @media screen and(max-width:1200px) {
      width: 80%;
    }
    .reply-input {
      min-height: 20px;
      line-height: 22px;
      padding: 10px 10px;
      color: #ccc;
      background-color: #fff;
      border-radius: 5px;
      // &:empty::before{
      //   content attr(placeholder);
      // }
      &:empty:before {
        content: attr(placeholder);
      }
      &:focus:before {
        content: none;
      }
      &:focus {
        padding: 8px 8px;
        border: 2px solid blue;
        box-shadow: none;
        outline: none;
      }
    }
  }
  .reply-btn-box {
    height: 25px;
    // margin: 10px 0;
    display: inline-block;
    .reply-btn {
      position: relative;
      float: right;
      margin-left: 15px;
      margin-top: 3px;
    }
  }
}
.my-comment-reply {
  margin-left: 50px;
  .reply-input {
    width: flex;
  }
}
.author-title:not(:last-child) {
  border-bottom: 1px solid #ebeef5;
}
.reply-father {
  padding: 10px;
  .header-img {
    display: inline-block;
    vertical-align: top;
  }
  .author-info {
    display: inline-block;
    margin-left: 5px;
    width: 60%;
    height: 40px;
    line-height: 20px;
    span {
      display: block;
      cursor: pointer;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
    .author-name {
      color: #000;
      font-size: 16px;
      font-weight: bold;
    }
    .author-time {
      font-size: 14px;
    }
  }
  .icon-btn {
    width: 30%;
    padding: 0 !important ;
    float: right;
    @media screen and (max-width: 1200px) {
      width: 20%;
      padding: 7px;
    }
    span {
      cursor: pointer;
    }
    .iconfont {
      margin: 0 5px;
    }
  }
  .talk-box {
    margin: 0 50px;
    p {
      margin: 0;
    }
    .reply {
      font-size: 16px;
      color: #000;
    }
  }
  .reply-box {
    margin: 10px 0 0 50px;
    background-color: #efefef;
  }
}
.reply-father .reply-box {
  margin: 10px 0 0 50px;
  background-color: #fff;
}
.el-collapse-item__content {
  padding-bottom: 0px;
  font-size: 13px;
  color: #303133;
  line-height: 1.769230769230769;
}
.box-card {
  margin-top: 5px;
  margin-bottom: 3px;
}
.comment-box {
  width: 80%;
}
.reply-father .icon-btn {
  width: 22%;
  padding: 7px;
}
</style>
